package com.golf.client.ui.chat;

import java.awt.BorderLayout;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import org.apache.log4j.Logger;
import org.jboss.remoting.Client;
import org.jboss.remoting.callback.Callback;

import com.golf.comms.client.ChatCallbackHandler;
import com.golf.comms.protocol.ChatMessage;

/**
 * 
 * 
 * @author gfloodgate
 */
public class ChatPanel extends Panel implements Runnable, ActionListener
{
	
	/** <code>serialVersionUID</code> for this class. */
    private static final long serialVersionUID = 3285074592849467432L;


    /** The logger instance. */
	private static transient final Logger log = Logger.getLogger(ChatPanel.class);

	
	/** The messaging client. */
	private Client client;
	
	/** The incoming message callback handler. */
	private transient ChatCallbackHandler callbackHandler;
	
	/** The flag indicating if the chat session is running. */
	private volatile boolean isRunning;
	
	
	private TextArea chatArea;
	private TextField textEntry;
	
	
	/**
	 * Create a chat panel instance.
	 */
	public ChatPanel()
	{
		setLayout(new BorderLayout());
		
		chatArea = new TextArea("");
		add(BorderLayout.NORTH, chatArea);
		
		textEntry = new TextField();
		textEntry.addActionListener(this);
		textEntry.setEnabled(false);
		add(BorderLayout.SOUTH, textEntry);
	}
	
	
	/**
	 * 
	 * 
	 * @throws Throwable
	 */
	public void attach(final Client instance) throws Throwable
	{
		if (!isRunning)
		{
			textEntry.setEnabled(true);
			
			client = instance;
			callbackHandler = new ChatCallbackHandler();
			client.addListener(callbackHandler);
			
			if (log.isDebugEnabled())
			{
				log.debug("Attached chat panel to client, ready for conversations.");
			}
			
			isRunning = true;
			final Thread chatThread = new Thread(this);
			chatThread.setDaemon(true);
			chatThread.start();
		}
	}
	
	
	/**
	 * 
	 * 
	 * @throws Throwable
	 */
	public void detach() throws Throwable
	{
		if (isRunning)
		{
			textEntry.setEnabled(false);

			isRunning = false;
			client.removeListener(callbackHandler);
			
			if (log.isDebugEnabled())
			{
				log.debug("Detached chat panel from client");
			}
		}
	}
	
	
	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
    public void run()
	{
		while (isRunning)
		{
			try
			{
				final List<Object> callbacks = client.getCallbacks(callbackHandler);
				if (callbacks != null)
				{
				    for (final Object obj : callbacks)
				    {
				    	final Callback callback = (Callback)obj;
				        final ChatMessage message = (ChatMessage)callback.getCallbackObject();
				        if (message != null)
				        {
				        	chatArea.append("[");
				        	chatArea.append(String.valueOf(message.getTime()));
				        	chatArea.append("] <");
				        	chatArea.append(message.getuser());
				        	chatArea.append("> ");
				        	chatArea.append(message.getMessage());
				        	chatArea.append("\n");
				        }
				    }	  
				}
				
			    Thread.sleep(100);
			} 
			catch (Throwable e)
			{
			    // TODO Auto-generated catch block
				e.printStackTrace();
			}
			    
		}
		
	}

	
	/**
	 * {@inheritDoc}
	 */
	public void actionPerformed(ActionEvent action)
	{
		try
		{
			// Create the chat message object, and send it.
			client.invoke(new ChatMessage("jim", textEntry.getText()) );
		
		
			textEntry.setText(null);
		}
		catch (Throwable t)
		{
			t.printStackTrace();
		}
	}

}
